package com.qiangqiang.task.server.service;

import com.qiangqiang.task.server.dto.MyRankingDTO;
import com.qiangqiang.task.server.entity.UserInfo;
import com.qiangqiang.task.server.mapper.UserMapper;
import com.qiangqiang.task.server.ranking.RankingTree;
import com.qiangqiang.task.server.ranking.entity.RankingUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: task
 * @description:
 * @author: Sky.lin
 * @create: 2019-02-13 16:15
 **/
@Service
public class RankingService {

    @Autowired
    RankingTree rankingTree;

    @Autowired
    UserMapper userMapper;

    public List<RankingUser> getTopNUser(int n) {
        return rankingTree.getTopN(n);
    }

    public MyRankingDTO getUserRanking(long userId) {
        UserInfo userInfo = userMapper.queryUserById(userId);
        RankingUser rankingUser = new RankingUser();// 构造rankingUser,用于查询
        BeanUtils.copyProperties(userInfo, rankingUser);
        MyRankingDTO myRankingDTO = new MyRankingDTO(); //用于返回的DTO类
        BeanUtils.copyProperties(userInfo, myRankingDTO);
        int ranking = rankingTree.getRanking(rankingUser.getAchievement(), rankingUser);
        myRankingDTO.setRanking(ranking);
        return myRankingDTO;
    }

    public void removeRankingUser(RankingUser rankingUser) {
        rankingTree.remove(rankingUser.getAchievement(), rankingUser);
    }

    public void insertRankingUser(RankingUser rankingUser) {
        rankingTree.insert(rankingUser.getAchievement(), rankingUser);
    }

    public void changeRanking(long userId, int value) {
        MyRankingDTO myRankingDTO = getUserRanking(userId);
        RankingUser rankingUser = new RankingUser();
        BeanUtils.copyProperties(myRankingDTO, rankingUser);
        rankingUser.setAchievement(myRankingDTO.getAchievement() + value);
        rankingTree.change(myRankingDTO.getAchievement(), rankingUser.getAchievement(), rankingUser);
        //持久化到数据库
        userMapper.updateAchievementByUserId(value, userId);
    }
}
